<template>
  <div class="table-page">
    <el-card>
      <!-- 顶部操作栏 -->
      <div class="toolbar">
        <el-button @click="showAddLand" type="primary" icon="Plus"
          >新增</el-button
        >
        <el-button type="danger" style="margin-left: 10px">批量删除</el-button>
        <el-select
          v-model="status"
          placeholder="状态"
          style="width: 120px; margin-left: 20px"
        >
          <el-option label="全部" value="全部"></el-option>
          <el-option label="闲置" value="闲置"></el-option>
          <el-option label="启用" value="启用"></el-option>
          <el-option label="弃用" value="弃用"></el-option>
        </el-select>
      </div>
      <!-- 表格 -->
      <el-table
        :data="filteredTableData"
        style="width: 100%; margin-top: 20px"
        @selection-change="handleSelectionChange"
        ref="tableRef"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" prop="id" label="ID" width="80" />
        <el-table-column prop="landName" label="名称" />
        <el-table-column prop="landsize" label="面积" />
        <el-table-column prop="climate" label="类型" />
        <el-table-column prop="isActive" label="状态" width="100">
          <template #default="{ row }">
            <el-dropdown @command="(command) => changeStatus(row, command)">
              <el-tag
                :type="
                  row.isActive == 1
                    ? 'success'
                    : row.isActive == 0
                    ? 'warning'
                    : 'danger'
                "
                style="cursor: pointer"
              >
                {{
                  row.isActive == "1"
                    ? "启用"
                    : row.isActive == "0"
                    ? "闲置"
                    : "弃用"
                }}
              </el-tag>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="1">启用</el-dropdown-item>
                  <el-dropdown-item command="0">闲置</el-dropdown-item>
                  <el-dropdown-item command="2">弃用</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" />
        <el-table-column label="操作" width="180">
          <template #default="{ row, $index }">
            <el-link
              type="primary"
              :underline="false"
              style="margin-right: 10px"
              @click="onEdit(row, $index)"
              >编辑</el-link
            >
            <el-link
              type="primary"
              :underline="false"
              style="margin-right: 10px"
              @click="onView(row, $index)"
              >查看</el-link
            >
            <el-link
              type="danger"
              :underline="false"
              @click="onDelete(row, $index)"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 新增/编辑弹窗 -->
      <el-dialog v-model="dialogVisible" :title="dialogTitle">
        <el-form :model="form" label-width="100px">
          <el-form-item label="用户id">
            <el-input v-model="form.id" />
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="form.landName" />
          </el-form-item>
          <el-form-item label="面积">
            <el-input
              v-model.number="form.landsize"
              type="number"
              placeholder="请输入土地面积（平方米）"
            />
          </el-form-item>
          <el-form-item label="类型">
            <el-input v-model="form.climate" />
          </el-form-item>
          <el-form-item label="土地地址">
            <el-input v-model="form.landAddress" />
          </el-form-item>
          <el-form-item label="上个农作物">
            <el-input v-model="form.previousCro" />
          </el-form-item>
          <el-form-item label="省">
            <el-select
              placeholder="请选择省"
              v-model="form.provinceCode"
              @change="onProvinceChange"
            >
              <el-option
                v-for="item in province"
                :key="item.areaId"
                :label="item.areaName"
                :value="item.areaId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="市">
            <el-select
              placeholder="请选择市"
              v-model="form.cityCode"
              @change="onCityChange"
            >
              <el-option
                v-for="item in city"
                :key="item.areaId"
                :label="item.areaName"
                :value="item.areaId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="区">
            <el-select placeholder="请选择区" v-model="form.areaCode">
              <el-option
                v-for="item in district"
                :key="item.areaId"
                :label="item.areaName"
                :value="item.areaId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="土地状态">
            <el-select v-model="form.isActive">
              <el-option label="闲置" :value="0" />
              <el-option label="启用" :value="1" />
              <el-option label="弃用" :value="2" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </template>
      </el-dialog>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next"
          :total="100"
          :page-size="10"
          :page-sizes="[10, 20, 50, 100]"
          v-model:current-page="currentPage"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, Ref, nextTick, watch } from "vue";
import { useGetAllLandStore } from "../../stores/land";
import {
  LandInfoData,
  LandInfoItem,
  positionItem,
  LandFormData,
  LandStatus,
  LandStatusOptions,
} from "../../types/land";
import {
  updateLandStatus,
  addLand,
  checkProvincesMunicipalities,
  deleteLandById,
  getLandById,
  updateLandById,
} from "../../api/farmer/land";
import { LandFormConverter } from "../../utils/landFormConverter";
import { ElMessage } from "element-plus";
import { onMounted } from "vue";
const getAllLandStore = useGetAllLandStore();
onMounted(async () => {
  await refreshTableData();
  getProvince();
});
const status = ref("");
const dateRange = ref<[Date, Date] | null>(null);
const currentPage = ref(1);
const tableRef = ref();
const multipleSelection = ref<any[]>([]);
//新增/编辑土地弹窗控制
const dialogVisible = ref(false);
//新增编辑查看弹窗标题
const dialogTitle = ref("新增地块");
//添加初始化对象，用于新增土地
//与新增编辑弹窗的数据双向绑定 - 使用正确的类型
const form = ref<LandFormData>({
  id: 0,
  landName: "玉米田22244",
  landsize: "2000",
  landQuality: "好",
  landImage: "",
  climate: "昼夜温差大",
  previousCro: "红薯",
  isActive: "1",
  landAddress: "天津渤海职业技术试验田",
  isPlanting: "",
  createTime: "",
  longitude: 0,
  latitude: 0,
  provinceCode: "天津市",
  cityCode: "市辖区",
  areaCode: "北辰区",
});
let editIndex = -1;

const tableData = ref<LandInfoItem[]>([]);
//新增：用于展示的过滤后数据
const filteredTableData = ref<LandInfoItem[]>([]);

//模拟提交表单数据
const demoAddForm = {
  id: 0,
  landName: "玉米田22244",
  landsize: "2000",
  landQuality: "好",
  landImage: "",
  climate: "昼夜温差大",
  previousCro: "红薯",
  isActive: "1",
  landAddress: "天津渤海职业技术试验田",
  isPlanting: "",
  createTime: "",
  longitude: 0,
  latitude: 0,
  provinceCode: "天津市",
  cityCode: "市辖区",
  areaCode: "北辰区",
};
//新增土地回调函数
const showAddLand = () => {
  editIndex = -1;
  dialogVisible.value = true;
  dialogTitle.value = "新增地块";
  // 重置表单为空数据
  form.value = {
    id: "",
    landName: "",
    landsize: "",
    landQuality: "",
    landImage: "",
    climate: "",
    previousCro: "",
    isActive: "",
    landAddress: "",
    isPlanting: "",
    createTime: "",
    longitude: 0,
    latitude: 0,
    provinceCode: "",
    cityCode: "",
    areaCode: "",
  };
  // 设置一些默认值
  form.value.landName = demoAddForm.landName;
  form.value.landQuality = demoAddForm.landQuality;
  form.value.landsize = demoAddForm.landsize;
  form.value.climate = demoAddForm.climate;
  form.value.previousCro = demoAddForm.previousCro;
  form.value.landAddress = demoAddForm.landAddress;
  form.value.provinceCode = demoAddForm.provinceCode;
  form.value.cityCode = demoAddForm.cityCode;
  form.value.areaCode = demoAddForm.areaCode;
  form.value.isActive = demoAddForm.isActive;
};

//查看土地详情
const onView = (row: any, index: number) => {
  dialogVisible.value = true;
  dialogTitle.value = "查看地块";
  form.value = row;
};

function handleSelectionChange(val: any[]) {
  multipleSelection.value = val;
}
// const viewForm = ref<LandFormData>({

// })
//编辑土地
async function onEdit(row: any, index: number) {
  try {
    dialogTitle.value = "编辑地块";
    let result = await getLandById(row.id);
    console.log("获取土地详情", result);
    form.value = result.data;
    console.log("编辑表单数据", form);

    editIndex = index;
    dialogVisible.value = true;
  } catch (error) {
    console.error("获取土地详情失败", error);
    ElMessage.error("获取土地详情失败");
  }
}
//删除土地
function onDelete(row: any, index: number) {
  console.log(row);
  deleteLandById(row.id);
  tableData.value.splice(index, 1);
}

//刷新表格数据
const refreshTableData = async () => {
  const params = {
    page: 1,
    size: 10,
  };
  await getAllLandStore.fetchLandInfo(params);
  const landInfo = getAllLandStore.landInfo;
  tableData.value = landInfo.data?.records ?? [];
  // 拉取数据后做一次过滤
  filterByStatus();
};

//新增编辑的提交按钮
async function onSubmit() {
  try {
    // 验证表单数据
    const validation = LandFormConverter.validateForm(form.value);
    if (!validation.valid) {
      ElMessage.error(validation.errors.join(", "));
      return;
    }

    if (editIndex === -1) {
      const result = await addLand(form.value);
      console.log("新增成功", result);
      ElMessage.success("新增土地成功");

      // 刷新表格数据
      await refreshTableData();
    } else {
      const result = await updateLandById(form.value);
      console.log("编辑成功", result);
      ElMessage.success("编辑土地成功");

      // 刷新表格数据
      await refreshTableData();
    }
    dialogVisible.value = false;
  } catch (error) {
    console.error("提交失败", error);
    ElMessage.error("操作失败，请重试");
  }
}

//修改土地状态
const changeStatus = (row: any, newStatus: any) => {
  // 这里可以做接口请求或本地修改
  console.log(row);
  row.isActive = String(newStatus);
  //0闲置，1启用，2弃用
  nextTick(() => {
    if (newStatus === "0") {
      let result = updateLandStatus(0, row.id);
      console.log(result);
    } else if (newStatus === "1") {
      let result = updateLandStatus(1, row.id);
      console.log(result);
    } else {
      let result = updateLandStatus(2, row.id);
      console.log(result);
    }
  });
};
//存储获取到的所有省数据
const province = ref<positionItem[]>([]);
//获取省数据
const getProvince = async () => {
  let result = await checkProvincesMunicipalities(0);
  province.value = result.data;
  console.log(province.value);
  console.log("省数据", result);
};

const city = ref<positionItem[]>([]);
const district = ref<positionItem[]>([]);

const onProvinceChange = async (provinceId: number) => {
  form.value.cityCode = "";
  form.value.areaCode = "";
  city.value = [];
  district.value = [];
  if (typeof provinceId === "number") {
    let result = await checkProvincesMunicipalities(provinceId);
    city.value = result.data || [];
  }
};

const onCityChange = async (cityId: number) => {
  form.value.areaCode = "";
  district.value = [];
  if (typeof cityId === "number") {
    let result = await checkProvincesMunicipalities(cityId);
    district.value = result.data || [];
  }
};

// 新增：根据状态过滤土地数据
const filterByStatus = () => {
  if (status.value === "" || status.value === "全部") {
    filteredTableData.value = tableData.value;
  } else {
    const statusMap: Record<string, string> = {
      闲置: "0",
      启用: "1",
      弃用: "2",
    };
    filteredTableData.value = tableData.value.filter(
      (item) => String(item.isActive) === statusMap[status.value]
    );
  }
};
// 监听status变化，切换时重新过滤
watch(status, () => {
  filterByStatus();
});
</script>

<style scoped>
.table-page {
  padding: 20px;
  background: #f5f6fa;
  min-height: 100vh;
}

.toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>